package com.swk.common.util.http;

import com.swk.common.exception.SwkException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017-6-8.
 */
public class HttpClientUtil {
    private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
    private static final int connectTimeout = 15000;
    private static final int soTimeout = 15000;

    /**
     * 请求格式json
     * @param args
     * @return
     * @throws Exception
     */
    public static String postURL(HashMap<String, String> args) throws Exception {
        String url = args.get("url");
        String postData = args.get("postData");

        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        postMethod.setRequestHeader("Accept-Language", "zh-CN,zh");
        postMethod.setRequestHeader("connection", "keep-alive");
        postMethod.setRequestHeader("content-type", "application/json");
        postMethod.setRequestHeader("pragma", "no-cache");

        byte[] b = null;
        InputStream is = null;
        InputStream respsonseStream = null;
        try {
            if (StringUtils.isNotEmpty(postData)) {
//                b = postData.getBytes("utf-8");
//                is = new ByteArrayInputStream(b, 0, b.length);
//                RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/json; charset=UTF-8");
//                postMethod.setRequestEntity(re);

                b = postData.getBytes("utf-8");
                RequestEntity re = new ByteArrayRequestEntity(b,"application/json; charset=UTF-8");
                postMethod.setRequestEntity(re);
            }
            HttpClient httpClient = new HttpClient();
            HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();
            httpConnectionManagerParams.setConnectionTimeout(connectTimeout);
            httpConnectionManagerParams.setSoTimeout(soTimeout);
            int status = httpClient.executeMethod(postMethod);
            logger.debug("method:[postURL],status:[" + status + "],getQueryString:[" + postMethod.getQueryString() + "],returnObj:[" + postMethod.getResponseBodyAsString() + "]");

            return getResponseString(postMethod);

            // returnBean.setSortMsg(postMethod.getResponseBodyAsString());
        } catch (Exception e) {
            throw e;
        } finally {
//            if (is != null) {
//                is.close();
//            }
//            if (stringReader != null) {
//                stringReader.close();
//            }
            if (respsonseStream != null) {
                respsonseStream.close();
            }
        }

        // return returnBean;
    }

    private static String getResponseString(PostMethod postMethod) {
//        try {
//            return postMethod.getResponseBodyAsString();
//        } catch (IOException e) {
//            e.printStackTrace();
//            logger.error("", e);
//        }
//        return null;
        InputStream respsonseStream = null;
        try{
            respsonseStream = postMethod.getResponseBodyAsStream();
            return IOUtils.toString(respsonseStream);
        } catch (Exception e) {
            logger.error("", e);
            e.printStackTrace();
        } finally {
            if (respsonseStream != null) {
                try {
                    respsonseStream.close();
                } catch (IOException e) {
                    logger.error("", e);
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 请求格式x-www-form-urlencoded
     * @param url
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, Object> paramMap) throws Exception {
        byte[] b = null;
        InputStream is = null;
//        StringReader stringReader = null;
        try {

            if (CollectionUtils.isNotEmpty(paramMap.keySet())) {
                PostMethod postMethod = new PostMethod(url);
                postMethod.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
                postMethod.setRequestHeader("Accept-Language", "zh-CN,zh");
                postMethod.setRequestHeader("connection", "keep-alive");
                postMethod.setRequestHeader("content-type", "application/x-www-form-urlencoded");
                postMethod.setRequestHeader("pragma", "no-cache");

                NameValuePair[] keyValueArr = new NameValuePair[paramMap.keySet().size()];
                int i = 0;
                for (String paramKey : paramMap.keySet()) {
                    NameValuePair keyValue = new NameValuePair();
                    keyValue.setName(paramKey);
                    Object value = paramMap.get(paramKey);
                    keyValue.setValue(value == null ? null : value.toString());
                    keyValueArr[i] = keyValue;
                    i = i + 1;
                }
                postMethod.setRequestBody(keyValueArr);

                HttpClient httpClient = new HttpClient();
                HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();
                httpConnectionManagerParams.setConnectionTimeout(connectTimeout);
                httpConnectionManagerParams.setSoTimeout(soTimeout);
                int status = httpClient.executeMethod(postMethod);
                logger.debug("method:[postURL],status:[" + status + "],getQueryString:[" + postMethod.getQueryString() + "],returnObj:[" + postMethod.getResponseBodyAsString() + "]");
                return getResponseString(postMethod);
            }else{
                throw new SwkException("paramMap is empty!");
            }
            // returnBean.setSortMsg(postMethod.getResponseBodyAsString());
        } catch (Exception e) {
            throw e;
        } finally {
//            if (is != null) {
//                is.close();
//            }
//            if (stringReader != null) {
//                stringReader.close();
//            }
        }

        // return returnBean;
    }


    /**
     * 请求格式x-www-form-urlencoded
     * @param url
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, String> requestHeaderMap, Map<String, Object> paramMap) throws Exception {
        byte[] b = null;
        InputStream is = null;
//        StringReader stringReader = null;
        try {

            if (CollectionUtils.isNotEmpty(paramMap.keySet())) {
                HttpClient httpClient = new HttpClient();

                // requestHeader
                PostMethod postMethod = new PostMethod(url);
                postMethod.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
                postMethod.setRequestHeader("Accept-Language", "zh-CN,zh");
                postMethod.setRequestHeader("connection", "keep-alive");
                postMethod.setRequestHeader("content-type", "application/x-www-form-urlencoded");
                postMethod.setRequestHeader("pragma", "no-cache");

                if (CollectionUtils.isNotEmpty(requestHeaderMap.keySet())) {
                    for (String headerKey : requestHeaderMap.keySet()) {
                        if (StringUtils.isNotBlank(headerKey)) {
                            postMethod.setRequestHeader(headerKey, requestHeaderMap.get(headerKey));
                        }
                    }
                }

//                // requestHeader new
//                List<Header> headers = new ArrayList<Header>();
//                if (CollectionUtils.isNotEmpty(requestHeaderMap.keySet())) {
//                    for (String headerKey : requestHeaderMap.keySet()) {
//                        if (StringUtils.isNotBlank(headerKey)) {
//                            headers.add(new Header(headerKey, requestHeaderMap.get(headerKey)));
//                        }
//                    }
//                }
//                httpClient.getHostConfiguration().getParams().setParameter(
//                        "http.default-headers", headers);

                // param
                NameValuePair[] keyValueArr = new NameValuePair[paramMap.keySet().size()];
                int i = 0;
                for (String paramKey : paramMap.keySet()) {
                    NameValuePair keyValue = new NameValuePair();
                    keyValue.setName(paramKey);
                    Object value = paramMap.get(paramKey);
                    keyValue.setValue(value == null ? null : value.toString());
                    keyValueArr[i] = keyValue;
                    i = i + 1;
                }
                postMethod.setRequestBody(keyValueArr);


                HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();
                httpConnectionManagerParams.setConnectionTimeout(connectTimeout);
                httpConnectionManagerParams.setSoTimeout(soTimeout);
                int status = httpClient.executeMethod(postMethod);
                logger.debug("method:[postURL],status:[" + status + "],getQueryString:[" + postMethod.getQueryString() + "],returnObj:[" + postMethod.getResponseBodyAsString() + "]");
                return getResponseString(postMethod);
            }else{
                throw new SwkException("paramMap is empty!");
            }
            // returnBean.setSortMsg(postMethod.getResponseBodyAsString());
        } catch (Exception e) {
            throw e;
        } finally {
//            if (is != null) {
//                is.close();
//            }
//            if (stringReader != null) {
//                stringReader.close();
//            }
        }

        // return returnBean;
    }

}
